package com.xs.gis.cover.coverImpl;

import com.xs.gis.cover.FileCover;
import com.xs.gis.domain.geojson.GeoFeature;
import com.xs.gis.domain.geojson.GeoJsonFeature;
import com.xs.gis.util.GisCommonUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.gdal.gdal.gdal;
import org.gdal.ogr.DataSource;
import org.gdal.ogr.Layer;
import org.gdal.ogr.ogr;
import org.gdal.osr.SpatialReference;

import java.util.List;

/**
 * @description:
 * @author: w
 * @create: 2023-08-18 10:09
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PostGISCover implements FileCover {

    private String defaultLayerName;

    private String defaultEpsgCode = "4490";


    public PostGISCover(String defaultLayerName) {
        this.defaultLayerName = defaultLayerName;
    }

    @Override
    public String featureToFile(GeoJsonFeature feature, String filePath) {

        gdal.AllRegister();
        // 自动注册所有可用的矢量数据驱动程序。OGR 是 GDAL 的矢量数据处理分支，支持 Shapefile、GeoJSON、KML、GPKG 等多种矢量格式，而该函数确保所有这些格式的读写支持被正确加载。
        ogr.RegisterAll();

        DataSource dataSource = ogr.Open(filePath);

        String epsgCode = StringUtils.isBlank(feature.getEpsgCode()) ? defaultEpsgCode : feature.getEpsgCode();

        List<GeoFeature> features = feature.getFeatures();
        Layer gdbLayer = dataSource.GetLayerByName(feature.getLayerName());
        if (gdbLayer == null) {
            gdbLayer = GisCommonUtils.createLayer(feature, dataSource, epsgCode,null);
        }
        //添加数据
        GisCommonUtils.addGdbData(features, gdbLayer, epsgCode);
        dataSource.delete();
        gdal.GDALDestroyDriverManager();

        return filePath;
    }


    @Override
    public GeoJsonFeature fileToFeature(String filePath) {

        gdal.AllRegister();
        ogr.RegisterAll();

        DataSource dataSource = ogr.Open(filePath);
        if (defaultLayerName == null) {
            throw new RuntimeException("请设置默认图层名称");
        }
        Layer layer = dataSource.GetLayerByName(defaultLayerName);
        GeoJsonFeature geoJsonFeature = new GeoJsonFeature();
        geoJsonFeature.setLayerName(layer.GetName());
        //设置图层名和参考系
        SpatialReference spatialReference = layer.GetSpatialRef();
        String epscCode = spatialReference == null ? defaultEpsgCode : spatialReference.GetAttrValue("AUTHORITY", 1);
        List<GeoFeature> features = GisCommonUtils.layerFeatureToFeature(epscCode, geoJsonFeature, layer);
        geoJsonFeature.setFeatures(features);

        layer.delete();
        dataSource.delete();
        gdal.GDALDestroyDriverManager();



        return geoJsonFeature;
    }




}
